<template>
    <el-container class="ep-layout">
        <el-aside width="220px" class="ep-aside">
            <div class="logo">LOGO</div>
            <el-scrollbar height="calc(100vh - 56px)">
                <el-menu
                    class="ep-menu"
                    :default-openeds="defaultOpeneds"
                    :unique-opened="false"
                    background-color="#2f3b52"
                    text-color="#cdd6e4"
                    active-text-color="#ffffff"
                >
                    <el-menu-item index="home">
                        <el-icon><House /></el-icon>
                        <span>门店管理</span>
                    </el-menu-item>
                    <el-menu-item index="stores">
                        <el-icon><List /></el-icon>
                        <span>查看门店</span>
                    </el-menu-item>
                    <el-menu-item index="admins">
                        <el-icon><User /></el-icon>
                        <span>管理员</span>
                    </el-menu-item>
                    <el-menu-item index="staff">
                        <el-icon><UserFilled /></el-icon>
                        <span>商家管理</span>
                    </el-menu-item>
                    <el-menu-item index="customers">
                        <el-icon><User /></el-icon>
                        <span>客户管理</span>
                    </el-menu-item>

                    <el-sub-menu index="rider">
                        <template #title>
                            <el-icon><Van /></el-icon>
                            <span>骑手管理</span>
                        </template>
                        <el-menu-item index="rider-audit">审核</el-menu-item>
                        <el-menu-item index="rider-status">状态</el-menu-item>
                        <el-menu-item index="rider-score">评分</el-menu-item>
                    </el-sub-menu>

                    <el-sub-menu index="orders">
                        <template #title>
                            <el-icon><Tickets /></el-icon>
                            <span>订单监控</span>
                        </template>
                        <el-menu-item index="orders-global">全局订单</el-menu-item>
                        <el-menu-item index="orders-exception">异常处理</el-menu-item>
                    </el-sub-menu>

                    <el-sub-menu index="reports">
                        <template #title>
                            <el-icon><DataAnalysis /></el-icon>
                            <span>数据报表</span>
                        </template>
                        <el-menu-item index="report-time">配送时效</el-menu-item>
                        <el-menu-item index="report-volume">订单量</el-menu-item>
                        <el-menu-item index="report-satisfaction">满意度</el-menu-item>
                    </el-sub-menu>

                    <el-menu-item index="settings">
                        <el-icon><Setting /></el-icon>
                        <span>系统设置</span>
                    </el-menu-item>
                </el-menu>
            </el-scrollbar>
        </el-aside>

        <el-container>
            <el-header class="ep-header">
                <div class="title">美客配送管理系统</div>
                <div class="user">
                    <el-avatar size="small">刘</el-avatar>
                    <div class="user-info">
                        <div class="name">刘金雷</div>
                        <el-tag size="small" type="success">老板</el-tag>
                    </div>
                </div>
            </el-header>
            <el-main class="ep-main">
                <el-card shadow="never" class="welcome-card">
                    <template #header>
                        <div class="card-header">
                            <el-icon><UserFilled /></el-icon>
                            <span class="card-title">欢迎使用美客配送管理系统</span>
                        </div>
                    </template>
                    <div class="hello">您好，刘金雷！</div>
                    <div class="meta">您的角色：老板｜登录时间：2025-08-26 15:14:49</div>
                    <el-alert
                        type="info"
                        :closable="false"
                        class="perm-alert"
                        title="您的权限：作为老板，您可以："
                        show-icon
                    />
                    <el-descriptions :column="2" border size="small" class="perm-desc">
                        <el-descriptions-item label="门店">管理门店信息</el-descriptions-item>
                        <el-descriptions-item label="人员">管理员工与人员</el-descriptions-item>
                        <el-descriptions-item label="订单">管理订单和服务</el-descriptions-item>
                        <el-descriptions-item label="客户">管理客户信息</el-descriptions-item>
                        <el-descriptions-item label="分析">查看统计分析</el-descriptions-item>
                        <el-descriptions-item label="设置">进行系统设置</el-descriptions-item>
                    </el-descriptions>
                </el-card>

                <el-card shadow="never" class="merchant-card">
                    <template #header>
                        <div class="merchant-header">
                            <div class="left">
                                <el-input v-model="keyword" placeholder="搜索用户名" clearable size="small" style="width: 200px;" @clear="reload">
                                    <template #prefix>
                                        <el-icon><Search /></el-icon>
                                    </template>
                                </el-input>
                                <el-button size="small" type="primary" @click="reload" style="margin-left: 8px;">查询</el-button>
                            </div>
                            <div class="right">
                                <el-button type="primary" size="small" @click="openAddDialog">添加商家</el-button>
                            </div>
                        </div>
                    </template>

                    <el-table :data="list" v-loading="loading" size="small" border>
                        <el-table-column prop="username" label="用户名" min-width="140" />
                        <el-table-column prop="phone" label="电话" min-width="120" />
                        <el-table-column prop="age" label="年龄" width="80" />
                        <el-table-column label="角色" min-width="120">
                            <template #default="scope">{{ scope.row.role?.name || '-' }}</template>
                        </el-table-column>
                        <el-table-column label="状态" width="100">
                            <template #default="scope">
                                <el-tag :type="scope.row.status ? 'success' : 'info'">{{ scope.row.status ? '启用' : '禁用' }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="创建时间" min-width="180">
                            <template #default="scope">{{ formatTime(scope.row.createTime) }}</template>
                        </el-table-column>
                        <el-table-column label="操作" width="180" fixed="right">
                            <template #default="scope">
                                <el-button link size="small" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
                                <el-divider direction="vertical" />
                                <el-popconfirm title="确认删除该商家吗？" @confirm="doDelete(scope.row._id)">
                                    <template #reference>
                                        <el-button link size="small" type="danger">删除</el-button>
                                    </template>
                                </el-popconfirm>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="pager">
                        <el-pagination
                            background
                            layout="total, prev, pager, next, sizes"
                            :total="total"
                            v-model:current-page="page"
                            v-model:page-size="pageSize"
                            :page-sizes="[5,10,20,50]"
                            @size-change="reload"
                            @current-change="reload"
                        />
                    </div>
                </el-card>

                <el-dialog v-model="addVisible" title="添加商家" width="520px">
                    <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="90px">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="addForm.username" />
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input v-model="addForm.password" type="password" show-password />
                        </el-form-item>
                        <el-form-item label="电话" prop="phone">
                            <el-input v-model="addForm.phone" />
                        </el-form-item>
                        <el-form-item label="年龄" prop="age">
                            <el-input-number v-model="addForm.age" :min="0" :max="120" />
                        </el-form-item>
                        <el-form-item label="角色ID" prop="roleId">
                            <el-input v-model="addForm.roleId" placeholder="请输入已有角色ID" />
                        </el-form-item>
                        <el-form-item label="状态">
                            <el-switch v-model="addForm.status" />
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="addVisible=false">取 消</el-button>
                            <el-button type="primary" @click="submitAdd">确 定</el-button>
                        </span>
                    </template>
                </el-dialog>

                <el-dialog v-model="editVisible" title="编辑商家" width="520px">
                    <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="90px">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="editForm.username" />
                        </el-form-item>
                        <el-form-item label="电话" prop="phone">
                            <el-input v-model="editForm.phone" />
                        </el-form-item>
                        <el-form-item label="年龄" prop="age">
                            <el-input-number v-model="editForm.age" :min="0" :max="120" />
                        </el-form-item>
                        <el-form-item label="角色ID" prop="roleId">
                            <el-input v-model="editForm.roleId" />
                        </el-form-item>
                        <el-form-item label="状态">
                            <el-switch v-model="editForm.status" />
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="editVisible=false">取 消</el-button>
                            <el-button type="primary" @click="submitEdit">保 存</el-button>
                        </span>
                    </template>
                </el-dialog>
            </el-main>
        </el-container>
    </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { House, List, User, UserFilled, Tickets, DataAnalysis, Setting, Van, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const defaultOpeneds = ref(["rider", "orders", "reports"]) // 默认展开

// 列表数据
const list = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const keyword = ref("")
const loading = ref(false)

const apiBase = '' // 同域部署时留空，若有前缀可在此配置

function formatTime(t) {
    if (!t) return '-'
    const d = new Date(t)
    const pad = (n) => String(n).padStart(2, '0')
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

async function fetchMerchants() {
    loading.value = true
    try {
        const params = new URLSearchParams({ page: String(page.value), pageSize: String(pageSize.value), keyword: keyword.value })
        const res = await fetch(`${apiBase}/admin/merchants?${params.toString()}`)
        const json = await res.json()
        if (json.code === 0) {
            list.value = json.data.list || []
            total.value = json.data.total || 0
        } else {
            ElMessage.error(json.message || '加载失败')
        }
    } catch (e) {
        ElMessage.error('请求失败')
    } finally {
        loading.value = false
    }
}

function reload() {
    fetchMerchants()
}

onMounted(() => {
    fetchMerchants()
})

// 添加商家
const addVisible = ref(false)
const addFormRef = ref()
const addForm = ref({ username: '', password: '', phone: '', age: 0, roleId: '', status: true })

const addRules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    roleId: [{ required: true, message: '请输入角色ID', trigger: 'blur' }],
}

function openAddDialog() {
    addForm.value = { username: '', password: '', phone: '', age: 0, roleId: '', status: true }
    addVisible.value = true
}

async function submitAdd() {
    try {
        await addFormRef.value.validate()
        const res = await fetch(`${apiBase}/admin/merchants`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(addForm.value)
        })
        const json = await res.json()
        if (json.code === 0) {
            ElMessage.success('添加成功')
            addVisible.value = false
            reload()
        } else {
            ElMessage.error(json.message || '添加失败')
        }
    } catch (e) {
        if (e?.message) {}
    }
}

// 编辑
const editVisible = ref(false)
const editFormRef = ref()
const editForm = ref({ _id: '', username: '', phone: '', age: 0, roleId: '', status: true })

const editRules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
}

function openEditDialog(row) {
    editForm.value = { _id: row._id, username: row.username, phone: row.phone || '', age: row.age || 0, roleId: row.role?._id || row.role, status: !!row.status }
    editVisible.value = true
}

async function submitEdit() {
    try {
        await editFormRef.value.validate()
        const payload = { username: editForm.value.username, phone: editForm.value.phone, age: editForm.value.age, roleId: editForm.value.roleId, status: editForm.value.status }
        const res = await fetch(`${apiBase}/admin/merchants/${editForm.value._id}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        })
        const json = await res.json()
        if (json.code === 0) {
            ElMessage.success('保存成功')
            editVisible.value = false
            reload()
        } else {
            ElMessage.error(json.message || '保存失败')
        }
    } catch (e) {
        if (e?.message) {}
    }
}

// 删除
async function doDelete(id) {
    try {
        const res = await fetch(`${apiBase}/admin/merchants/${id}`, { method: 'DELETE' })
        const json = await res.json()
        if (json.code === 0) {
            ElMessage.success('删除成功')
            reload()
        } else {
            ElMessage.error(json.message || '删除失败')
        }
    } catch (e) {
        ElMessage.error('请求失败')
    }
}
</script>

<style scoped>
.ep-layout {
    min-height: 100vh;
    background: #f5f7fa;
}

.ep-aside {
    background: #2f3b52;
    color: #cdd6e4;
}

.logo {
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    color: #ffffff;
    background: #253047;
}

.ep-menu {
    border-right: none;
}

.ep-header {
    height: 56px;
    background: #253047;
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
}

.title {
    font-size: 16px;
    font-weight: 600;
}

.user {
    display: flex;
    align-items: center;
    gap: 10px;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.ep-main {
    padding: 16px;
}

.welcome-card :deep(.el-card__header) {
    padding: 12px 16px;
}

.card-header {
    display: flex;
    align-items: center;
    gap: 8px;
}

.card-title {
    font-weight: 600;
}

.hello {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 6px;
}

.meta {
    font-size: 12px;
    color: #6b7280;
    margin-bottom: 12px;
}

.perm-alert {
    margin-bottom: 12px;
}

.perm-desc {
    background: #fff;
}

.merchant-card {
    margin-top: 16px;
}

.merchant-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.pager {
    display: flex;
    justify-content: flex-end;
    padding: 12px 0 4px;
}
</style>